package org.java.common;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;


import org.apache.commons.io.FileUtils;
import org.apache.commons.io.LineIterator;

public class FileHelper {
	final static String FILE_NAME = "/home/test.txt";

	private File getPath() {
		try {
			File file = new File(FILE_NAME);
			if (!file.exists()) {
				file.createNewFile();
			}
			return file;
		} catch (Exception e) {
			return null;
		}
	}

	public void print() {
		FileReader fileReader = null;
		BufferedReader br = null;
		try {
			fileReader = new FileReader(getPath());
			br = new BufferedReader(fileReader);
			while (br.ready()) {
				System.out.println(br.readLine());
			}
		} catch (Exception e) {
		} finally {
			try {
				fileReader.close();
			} catch (Exception e2) {
			}

			try {
				br.close();
			} catch (Exception e2) {
			}
		}
	}

	public void search(String str) {
		FileReader fileReader = null;
		BufferedReader br = null;
		try {
			fileReader = new FileReader(getPath());
			br = new BufferedReader(fileReader);
			while (br.ready()) {
				String line = br.readLine();
				if (line.indexOf(str) >= 0) {
					System.out.println(line);
				}
			}
		} catch (Exception e) {
		} finally {
			try {
				fileReader.close();
			} catch (Exception e2) {
			}

			try {
				br.close();
			} catch (Exception e2) {
			}
		}
	}

	public void find(String str) {
		LineIterator it = null;
		try {
			it = FileUtils.lineIterator(getPath(), "UTF-8");
			while (it.hasNext()) {
				String line = it.nextLine();
				if (line.indexOf(str) >= 0) {
					System.out.println(line);
				}
			}
		} catch (Exception e) {
		} finally {
			try {
				LineIterator.closeQuietly(it);
			} catch (Exception e2) {
			}
		}
	}

	public void write(String tag) {
		FileWriter fileWriter = null;
		BufferedWriter bufferedWriter = null;
		try {
			fileWriter = new FileWriter(getPath(), true);
			bufferedWriter = new BufferedWriter(fileWriter);
			for (int i = 0; i < 10000; i++) {
				bufferedWriter
						.append(String.format("time[%d] cost[%d] function[%s]",System.nanoTime(), i, tag));
				bufferedWriter.newLine();
				Thread.sleep(3);
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				fileWriter.close();
			} catch (Exception e2) {
			}

			try {
				bufferedWriter.close();
			} catch (Exception e2) {
			}
		}
	}
}
